/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.servlet;

import com.util.SQLConnection;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.annotation.Resource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
/**
 *
 * @author chetans
 */


public class NewTaskServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */

    private Connection con;
    private PreparedStatement pstmt;
    private ResultSet rs;

    private Logger myLogger = Logger.getLogger("RootLogger");

    private boolean checkAvailability(String taskName)throws Exception {
       myLogger.info("Entering with task name :"+taskName);
       boolean isTaskNameAvailable = true;
       con = new SQLConnection().getMySQLConnection();
       pstmt = con.prepareStatement("select task_name from tasks where task_name like ?");
       pstmt.setString(1, taskName);
       rs = pstmt.executeQuery();
       int numberOfRows=0;
      while(rs.next()){
          numberOfRows++;
      }
       if(numberOfRows>0){
           isTaskNameAvailable = false;
           myLogger.info(taskName+" already exists..");
       }
       myLogger.info("Exiting..");
       return isTaskNameAvailable;
    }

    private void saveTask(HttpServletRequest request,PrintWriter out) {
        myLogger.info("Entering..");
        try{
           String taskName = request.getParameter("task_name");
           myLogger.info("Task name entered by the user :"+taskName);

           boolean isTaskNameAvailable=checkAvailability(taskName);
           myLogger.info("isTaskNameAvailable :"+isTaskNameAvailable);

            if(isTaskNameAvailable){
                con =new SQLConnection().getMySQLConnection();
                pstmt = con.prepareStatement("insert into tasks values ('0',?)");
                pstmt.setString(1, taskName);
                int reuslt = pstmt.executeUpdate();
                if(reuslt == 0)
                    out.println("Task NOT saved. Internal Error");
                else
                    out.println("Task saved");
              }
            else{
            out.print("Task already exists. Please enter a different task");
         }
          myLogger.info("Exiting..");
        }catch(SQLException SQLE) {
            SQLE.printStackTrace();
            myLogger.error("SQLException :"+SQLE);
        }catch(Exception e){
            e.printStackTrace();
            myLogger.error("Exception :"+e);
        }
    }
    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        myLogger.info("Entering..");
        PrintWriter out = response.getWriter();
        try {
            saveTask(request,out);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Exception in DB transaction.");
        }
        myLogger.info("Exiting..");
    }
}
